import { login, logout, getInfo, refreshToken } from '@/api/login'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    refreshToken: getRefreshToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    staffId: '',
    staffName: '',
    userName: '',
    phoneNumber: '',
    email: '',
    companyId: '',
    hospitalId: '',
    departmentId: '',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_STAFF_ID: (state, staffId) => {
      state.staffId = staffId
    },
    SET_USER_NAME: (state, userName) => {
      state.userName = userName
    },
    SET_STAFF_NAME: (state, staffName) => {
      state.staffName = staffName
    },
    SET_PHONE_NUMBER: (state, phoneNumber) => {
      state.phoneNumber = phoneNumber
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_COMPANY_ID: (state, companyId) => {
      state.companyId = companyId
    },
    SET_HOSPITAL_ID: (state, hospitalId) => {
      state.hospitalId = hospitalId
    },
    SET_DEPARTMENT_ID: (state, departmentId) => {
      state.departmentId = departmentId
    },
  },

  actions: {
    // 登录
    Login({ commit }, loginObj) {
      const username = loginObj.username.trim()
      const password = loginObj.password
      const code = loginObj.code
      const uuid = loginObj.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid, loginObj.grantType).then(res => {
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          setRefreshToken(res.data.refreshToken)
          commit('SET_REFRESH_TOKEN', res.data.refreshToken)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新令牌
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        if (state.refreshToken) {
          refreshToken(state.refreshToken).then(res => {
            setToken(res.data.token)
            commit('SET_TOKEN', res.data.token)
            setRefreshToken(res.data.refreshToken)
            commit('SET_REFRESH_TOKEN', res.data.refreshToken)
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else {
          reject('refreshToken is not find')
        }
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const data = res.data
          const avatar = (data.avatar == "" || data.avatar == null) ? require("@/assets/images/default-profile.png") : data.avatar;
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            localStorage.setItem('user-Roles', data.roles)
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', data.userName)
          commit('SET_AVATAR', avatar)
          commit('SET_STAFF_ID', data.staffId)
          commit('SET_STAFF_NAME', data.staffName)
          localStorage.setItem('user-Name', data.userName)
          commit('SET_USER_NAME', data.userName)
          localStorage.setItem('User-Phone', data.phoneNumber)
          commit('SET_PHONE_NUMBER', data.phoneNumber)
          localStorage.setItem('User-Email', data.email)
          commit('SET_EMAIL', data.email)
          localStorage.setItem('User-CompanyId', data.companyId)
          commit('SET_COMPANY_ID', data.companyId)
          localStorage.setItem('User-HospitalId', data.hospitalId)
          commit('SET_HOSPITAL_ID', data.hospitalId)
          localStorage.setItem('User-DepartmentId', data.departmentId)
          commit('SET_DEPARTMENT_ID', data.departmentId)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          removeRefreshToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        removeToken()
        removeRefreshToken()
        resolve()
      })
    }
  }
}

export default user
